package tt.dz.egobus.servicemanager.business.task.job;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import tt.dz.egobus.api.ResponseBack;
import tt.dz.egobus.servicemanager.business.key.BusinessCache;
import tt.dz.egobus.servicemanager.service.GrabManagerService;

import java.util.Map;

/**
 * @author Anson
 * @date 17-8-9
 * @name 司机抢单超时
 * @since 1.0.6
 */
public class DriverGrabBusinessTimeout extends BusinessCacheGrabDynamicTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(DriverGrabBusinessTimeout.class);

    /**
     * @author Anson
     * @date 17-8-9
     * @name 司机抢单超时jobDataMap的key
     * @since 1.0.6
     */
    public enum DriverGrabBusinessParamey {
        ;
        private String key;

        DriverGrabBusinessParamey(String key) {
            this.key = key;
        }

        public String getKey() {
            return key;
        }
    }

    @Override
    public void timeout(Map<String, Object> jobDatamap) {
        String businessId = this.getBusinessId(jobDatamap);
        LOGGER.info("当前业务抢单超时,businessId={}", businessId);
        if (StringUtils.isBlank(businessId)) {
            return;
        }
        ApplicationContext applicationContext = this.getSpringContext();
        GrabManagerService grabManagerService =
                applicationContext.getBean("grabManagerServiceImpl", GrabManagerService.class);
        ResponseBack<Boolean> isSuccess = grabManagerService.doGrabTimeout(businessId);
        if (isSuccess.isSuccess() && isSuccess.getResult()) {
            //系统派单成功之后
            grabManagerService.pushBusinessHandler(businessId);
        }
        grabManagerService.terminalDynamicTask(businessId);
    }

    @Override
    protected boolean isInit(Map<String, Object> jobDatamap) {
        return true;
    }

    @Override
    protected boolean isTimeout(Map<String, Object> jobDatamap) {
        BusinessCache cache = this.getBusinessCache(jobDatamap);
        if (cache == null) {
            return false;
        }
        Long createDate = cache.getCreateDate();
        Long limitTimeoutSeconds = cache.getGrabLimitTimeoutSeconds();
        Long limitTimeoutMilliseconds = limitTimeoutSeconds * 1000L;
        Long currentTime = System.currentTimeMillis();
        //当前时间点 > 创建时间点 + 超时时间毫秒数
        return currentTime >= createDate + limitTimeoutMilliseconds;
    }

}
